package io.mvvm.nio.channel;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @program: Netty
 * @description: FileChannel 文件拷贝
 * @author: 潘
 * @create: 2021-01-17 21:06
 **/
public class FileChannelCopyExample {
    public static void main(String[] args) throws Exception {
        FileInputStream inputStream = new FileInputStream("E:\\work\\Netty\\nio\\src\\main\\resources\\fileName.txt");
        FileChannel inputStreamChannel = inputStream.getChannel();

        FileOutputStream outputStream = new FileOutputStream("E:\\work\\Netty\\nio\\src\\main\\resources\\fileName2.txt");
        FileChannel outputStreamChannel = outputStream.getChannel();

        ByteBuffer buffer = ByteBuffer.allocate(1024);

        // 循环读取
        while (true) {
            // 清除 buffer
            buffer.clear();
            int read = inputStreamChannel.read(buffer);
            if (read == -1) {
                // 读取完毕
                break;
            }

            // 将 buffer 中数据写入到 outputStreamChannel 中
            // 读写转换
            buffer.flip();
            outputStreamChannel.write(buffer);
        }
        outputStreamChannel.close();
        inputStreamChannel.close();
    }
}
